package org.zero.onlinesubject.service.impl;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.net.URLEncodeUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.zero.onlinesubject.common.vo.TokenInfo;
import org.zero.onlinesubject.common.vo.WxUserInfo;
import org.zero.onlinesubject.config.WxConfig;
import org.zero.onlinesubject.entity.Role;
import org.zero.onlinesubject.service.RoleService;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@Service
@Slf4j
public class QrService {

    @Resource
    private WxConfig wxConfig;

    @Resource
    private RoleService roleService;

    public WxUserInfo getUserInfo(String code,String state){

        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+wxConfig.getAppid()+"&secret="+wxConfig.getSecret()+"&code="+code+"&grant_type=authorization_code";

        HttpRequest request = HttpUtil.createGet(url, true);
        HttpResponse response = request.execute();

        WxUserInfo wxUserInfo = null;
        // 拉取用户信息
        if(response.getStatus() == 200){
            TokenInfo tokenInfo = JSON.parseObject(response.body(), TokenInfo.class);
            String url2 = "https://api.weixin.qq.com/sns/userinfo?access_token="+tokenInfo.getAccess_token()+"&openid="+tokenInfo.getOpenid()+"&lang=zh_CN";
            HttpRequest request2 = HttpUtil.createGet(url2, true);
            HttpResponse response2 = request2.execute();

            if (response2.getStatus() == 200) {
                wxUserInfo = JSON.parseObject(response2.body(), WxUserInfo.class);
            }
        }

        return wxUserInfo;
    }

    public String getQRCode(String uuid) {
        String encodedUrl = URLEncodeUtil.encode(wxConfig.getRedirectUrl());
        String STATE = uuid;
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+wxConfig.getAppid()+"&redirect_uri="+encodedUrl+"&response_type=code&scope=snsapi_userinfo&state="+STATE+"&forcePopup=true#wechat_redirect";

        QrConfig config = new QrConfig(300, 300);
        config.setErrorCorrection(ErrorCorrectionLevel.M);
        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();

            QrCodeUtil.generate(url,config,"png",baos);

            return "data:image/png;base64," + Base64Encoder.encode(baos.toByteArray());
        } finally {
            try {
                baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

